import { defineComponent, reactive, ref, toRefs } from 'vue'
import {
  NInput,
  NForm,
  NFormItem,
  NModal,
  NSelect,
  FormRules,
  NRadioGroup,
  NSpace,
  NRadio
} from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { addDataRelatedReq } from '@/service/modules/data-manage'
import { useDatasource } from '../../common/use-datasource'

const AddDataRelatedModal = defineComponent({
  name: 'AddDataRelatedModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    datasourceId: {
      type: Number,
      required: true
    },
    dbName: {
      type: String,
      required: true
    },
    tableName: {
      type: String,
      required: true
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      form: {
        currentDatasourceId: 0,
        currentDbName: '',
        currentTableName: '',
        relation: 'UPSTREAM',
        datasourceId: null,
        dbType: '',
        datasourceName: '',
        dbName: '',
        tableName: '',
        taskName: ''
      },
      rules: {
        dbType: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.dbType === '') {
              return new Error(window.$t('dataManage.datasourceTypeTips'))
            }
          }
        },
        datasourceName: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.datasourceName === '') {
              return new Error(window.$t('dataManage.selectDatasourceTips'))
            }
          }
        },
        dbName: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.dbName === '') {
              return new Error(window.$t('dataManage.selectDbTips'))
            }
          }
        },
        tableName: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.form.tableName === '') {
              return new Error(window.$t('dataManage.selectTableTips'))
            }
          }
        }
      } as FormRules,
      positiveButtonDisabled: ref(false)
    })
    //数据源类型下拉选项
    const {
      dsVariables,
      getDsTypeOptions,
      getDatasourceByType,
      getDbsByDatasourceId,
      getTablesByDsAndDb
    } = useDatasource()
    getDsTypeOptions()
    return {
      ...toRefs(state),
      dsVariables,
      getDatasourceByType,
      getDbsByDatasourceId,
      getTablesByDsAndDb
    }
  },
  methods: {
    async onPositiveClick() {
      //提交添加数据血缘请求
      this.positiveButtonDisabled = true
      this.form.currentDatasourceId = this.datasourceId
      this.form.currentDbName = this.dbName
      this.form.currentTableName = this.tableName
      const res: Response<any> = await addDataRelatedReq({
        ...this.form
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.form.relation = 'UPSTREAM'
      this.form.datasourceId = null
      this.form.dbType = ''
      this.form.datasourceName = ''
      this.form.dbName = ''
      this.form.tableName = ''
      this.form.taskName = ''
    },
    handleDsTypeChange(value: string) {
      this.form.datasourceId = null
      this.form.datasourceName = ''
      this.form.dbName = ''
      this.form.tableName = ''
      this.getDatasourceByType(value)
      this.dsVariables.dbOptions = []
      this.dsVariables.tableOptions = []
    },
    handleDsChange(value: number, label: string) {
      this.form.datasourceName = label
      this.form.dbName = ''
      this.form.tableName = ''
      this.getDbsByDatasourceId(value)
      this.dsVariables.tableOptions = []
    },
    handleDbChange(value: string) {
      this.form.tableName = ''
      this.getTablesByDsAndDb(
        this.form.datasourceId ? this.form.datasourceId : 0,
        value
      )
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('dataManage.addRelated')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        onClose={this.onNegativeClick}
        positiveButtonProps={{
          disabled:
            this.positiveButtonDisabled ||
            this.form.dbType === '' ||
            !this.form.datasourceId ||
            this.form.dbName === '' ||
            this.form.tableName === ''
        }}
      >
        <NForm
          rules={this.rules}
          label-placement='left'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem path='relation' label={window.$t('dataManage.relation')}>
            <NRadioGroup
              v-model={[this.form.relation, 'value']}
              name='sexGroup'
            >
              <NSpace>
                <NRadio value='UPSTREAM'>
                  {window.$t('dataManage.upstreamTable')}
                </NRadio>
                <NRadio value='DOWNSTREAM'>
                  {window.$t('dataManage.downstreamTable')}
                </NRadio>
              </NSpace>
            </NRadioGroup>
          </NFormItem>
          <NFormItem
            path='dbType'
            label={window.$t('dataManage.datasourceType')}
          >
            <NSelect
              v-model={[this.form.dbType, 'value']}
              options={this.dsVariables.dsTypeOptions}
              size='small'
              onUpdateValue={this.handleDsTypeChange}
            />
          </NFormItem>
          <NFormItem
            path='datasourceName'
            label={window.$t('dataManage.datasourceName')}
          >
            <NSelect
              v-model={[this.form.datasourceId, 'value']}
              options={this.dsVariables.dsOptions}
              size='small'
              onUpdateValue={this.handleDsChange}
            />
          </NFormItem>
          <NFormItem path='dbName' label={window.$t('dataManage.dbName')}>
            <NSelect
              v-model={[this.form.dbName, 'value']}
              options={this.dsVariables.dbOptions}
              size='small'
              onUpdateValue={this.handleDbChange}
            />
          </NFormItem>
          <NFormItem path='tableName' label={window.$t('dataManage.table')}>
            <NSelect
              v-model={[this.form.tableName, 'value']}
              options={this.dsVariables.tableOptions}
              size='small'
            />
          </NFormItem>
          <NFormItem
            path='taskName'
            label={window.$t('dataManage.relevanceTask')}
          >
            <NInput
              type='text'
              v-model={[this.form.taskName, 'value']}
            ></NInput>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default AddDataRelatedModal
